{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Copyright 2019 Google LLC\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Getting started with AutoML Tables\n",
    "\n",
    "<table align=\"left\">\n",
    "  <td>\n",
    "    <a href=\"https://cloud.google.com/ml-engine/docs/tensorflow/getting-started-keras\">\n",
    "      <img src=\"https://cloud.google.com/_static/images/cloud/icons/favicons/onecloud/super_cloud.png\"\n",
    "           alt=\"Google Cloud logo\" width=\"32px\"> Read on cloud.google.com\n",
    "    </a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"\">\n",
    "      <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
    "    </a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"\">\n",
    "      <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
    "      View on GitHub\n",
    "    </a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "b--5FDDwCG9C"
   },
   "source": [
    "## Overview\n",
    "\n",
    "[Google’s AutoML](https://cloud.google.com/automl-tables/) provides the ability for software engineers to build high quality models without the need to know how to build, train models, or deploy/serve models on the cloud. Instead, one only needs to know about dataset curation, evaluating results, and the how-to steps.\n",
    "\n",
    "<img src=\"https://cloud.google.com/images/automl-tables/automl-table.svg\" alt=\"AutoML tables\" width=\"600px\">\n",
    "\n",
    "AutoML Tables is a supervised learning service. This means that you train a machine learning model with example data. AutoML Tables uses tabular (structured) data to train a machine learning model to make predictions on new data. One column from your dataset, called the target, is what your model will learn to predict. Some number of the other data columns are inputs (called features) that the model will learn patterns from. \n",
    "\n",
    "In this notebook, we will use the [Google Cloud SDK AutoML Python API](https://cloud.google.com/automl-tables/docs/client-libraries) to create a binary classification model using a real dataset from the [Census Income Dataset](https://archive.ics.uci.edu/ml/datasets/Census+Income).\n",
    "\n",
    "We will provide the training and evaluation dataset, once dataset is created we will use AutoML API to create the model and then perform predictions to predict if a given individual has an income above or below 50k, given information like the person's age, education level, marital-status, occupation etc... \n",
    "\n",
    "For setting up a Google Cloud Platform (GCP) account for using AutoML, please see the online documentation for [Getting Started](https://cloud.google.com/automl-tables/docs/quickstart).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset\n",
    "\n",
    "This tutorial uses the [United States Census Income\n",
    "Dataset](https://archive.ics.uci.edu/ml/datasets/census+income) provided by the\n",
    "[UC Irvine Machine Learning\n",
    "Repository](https://archive.ics.uci.edu/ml/index.php)containing information about people from a 1994 Census database, including age, education, marital status, occupation, and whether they make more than $50,000 a year. The dataset consists of over 30k rows, where each row corresponds to a different person. For a given row, there are 14 features that the model conditions on to predict the income of the person. A few of the features are named above, and the exhaustive list can be found both in the dataset link above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "AZs0ICgy4jkQ"
   },
   "source": [
    "## Before you begin\n",
    "\n",
    "Follow the [AutoML Tables documentation](https://cloud.google.com/automl-tables/docs/) to:\n",
    "* Create a Google Cloud Platform (GCP) project.\n",
    "* Enable billing.\n",
    "* Apply to whitelist your project.\n",
    "* Enable AutoML API.\n",
    "\n",
    "You also need to upload your data into [Google Cloud Storage](https://cloud.google.com/storage/) (GCS) or [BigQuery](https://cloud.google.com/bigquery/). \n",
    "For example, to use GCS as your data source:\n",
    "\n",
    "* [Create a GCS bucket](https://cloud.google.com/storage/docs/creating-buckets).\n",
    "* Upload the training and batch prediction files."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xZECt1oL429r"
   },
   "source": [
    "\n",
    "\n",
    "---\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Instructions\n",
    "\n",
    "You must do several things before you can train and deploy a model in\n",
    "AutoML:\n",
    "\n",
    "\n",
    " * Set up your local development environment (optional)\n",
    " * Set Project ID and Compute Region\n",
    " * Authenticate your GCP account\n",
    " * Import Python API SDK and create a Client instance,\n",
    " * Create a dataset instance and import the data.\n",
    " * Create a model instance and train the model.\n",
    " * Evaluating the trained model.\n",
    " * Deploy the model on the cloud for online predictions.\n",
    " * Make online predictions.\n",
    " * Undeploy the model\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set up your local development environment\n",
    "\n",
    "**If you are using Colab or AI Platform Notebooks**, your environment already meets\n",
    "all the requirements to run this notebook. You can skip this step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set up your GCP project\n",
    "\n",
    "**The following steps are required, regardless of your notebook environment.**\n",
    "\n",
    "1. [Select or create a GCP project.](https://console.cloud.google.com/cloud-resource-manager)\n",
    "\n",
    "2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
    "\n",
    "3. [Enable the AutoML API (\"AutoML API\")](https://console.cloud.google.com/flows/enableapi?apiid=automl.googleapis.com)\n",
    "\n",
    "4. Enter your project ID in the cell below. Then run the  cell to make sure the\n",
    "Cloud SDK uses the right project for all the commands in this notebook.\n",
    "\n",
    "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "PROJECT_ID = \"<your-project-id>\" # @param {type:\"string\"}\n",
    "COMPUTE_REGION = \"us-central1\" # Currently only supported region.\n",
    "! gcloud config set project $PROJECT_ID"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Authenticate your GCP account\n",
    "\n",
    "**If you are using AI Platform Notebooks**, your environment is already\n",
    "authenticated. Skip this step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**If you are using Colab**, run the cell below and follow the instructions\n",
    "when prompted to authenticate your account via oAuth.\n",
    "\n",
    "**Otherwise**, follow these steps:\n",
    "\n",
    "1. In the GCP Console, go to the [**Create service account key**\n",
    "   page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
    "\n",
    "2. From the **Service account** drop-down list, select **New service account**.\n",
    "\n",
    "3. In the **Service account name** field, enter a name.\n",
    "\n",
    "4. From the **Role** drop-down list, select\n",
    "   **AutoML > AutoML Admin** and\n",
    "   **Storage > Storage Object Admin**.\n",
    "\n",
    "5. Click *Create*. A JSON file that contains your key downloads to your\n",
    "local environment.\n",
    "\n",
    "6. Enter the path to your service account key as the\n",
    "`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "# If you are running this notebook in Colab, run this cell and follow the\n",
    "# instructions to authenticate your GCP account. This provides access to your\n",
    "# Cloud Storage bucket and lets you submit training jobs and prediction\n",
    "# requests.\n",
    "\n",
    "if 'google.colab' in sys.modules:    \n",
    "  from google.colab import files\n",
    "  keyfile_upload = files.upload()\n",
    "  keyfile = list(keyfile_upload.keys())[0]\n",
    "  %env GOOGLE_APPLICATION_CREDENTIALS $keyfile\n",
    "# If you are running this notebook locally, replace the string below with the\n",
    "# path to your service account key and run this cell to authenticate your GCP\n",
    "# account.\n",
    "else:\n",
    "  %env GOOGLE_APPLICATION_CREDENTIALS /path/to/service_account.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BR0POq2UzE7e"
   },
   "source": [
    "### Install the client library\n",
    "Run the following cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "43aXKjDRt_qZ"
   },
   "outputs": [],
   "source": [
    "%pip install google-cloud-automl"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import libraries and define constants\n",
    "\n",
    "First, import Python libraries required for training,\n",
    "The code example below demonstrates importing the AutoML Python API module into a python script. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# AutoML library\n",
    "from google.cloud import automl_v1beta1 as automl\n",
    "\n",
    "import google.cloud.automl_v1beta1.proto.data_types_pb2 as data_types\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Quickstart for AutoML tables\n",
    "\n",
    "This section of the tutorial walks you through creating an AutoML Tables client."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, one will want to create an instance to the TablesClient.  \n",
    "This client instance is the HTTP request/response interface between the python script and the GCP AutoML service."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create API Client to AutoML Service*\n",
    "\n",
    "**If you are using AI Platform Notebooks**, or *Colab* environment is already\n",
    "authenticated using GOOGLE_APPLICATION_CREDENTIALS. Run this step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "client = automl.TablesClient(project=PROJECT_ID, region=COMPUTE_REGION)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "rUlBcZ3OfWcJ"
   },
   "source": [
    "**If you are using Colab or Jupyter**, and you have defined a service account\n",
    "follow the following steps to create the AutoML client\n",
    "\n",
    "You can see a different way to create the API Clients using service account."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# from google.oauth2 import service_account\n",
    "# credentials = service_account.Credentials.from_service_account_file('/path/to/service_account.json')\n",
    "# client = automl.TablesClient(project=PROJECT_ID, region=COMPUTE_REGION, credentials=credentials)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "List datasets in your project:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {},
    "colab_type": "code",
    "id": "sf32nKXIqYje"
   },
   "outputs": [],
   "source": [
    "# List datasets in Project\n",
    "list_datasets = client.list_datasets()\n",
    "datasets = { dataset.display_name: dataset.name for dataset in list_datasets }\n",
    "datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "t9uE8MvMkOPd"
   },
   "source": [
    "You can also print the list of your models by running the following cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {},
    "colab_type": "code",
    "id": "j4-bYRSWj7xk"
   },
   "outputs": [],
   "source": [
    "list_models = client.list_models()\n",
    "models = { model.display_name: model.name for model in list_models }\n",
    "models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "qozQWMnOu48y"
   },
   "source": [
    "\n",
    "\n",
    "---\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "XwjZc9Q62Fm5"
   },
   "source": [
    "### Create a dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_JfZFGSceyE_"
   },
   "source": [
    "Now we are ready to create a dataset instance (on GCP) using the client method create_dataset(). This method has one required parameter, the human readable display name `dataset_display_name`.\n",
    "\n",
    "Select a dataset display name and pass your table source information to create a new dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Z_JErW3cw-0J"
   },
   "outputs": [],
   "source": [
    "# Create dataset\n",
    "\n",
    "dataset_display_name = 'census' \n",
    "dataset = client.create_dataset(dataset_display_name)\n",
    "dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "35YZ9dy34VqJ"
   },
   "source": [
    "### Import data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "3c0o15gVREAw"
   },
   "source": [
    "You can import your data to AutoML Tables from GCS or BigQuery. For this tutorial, you can use the [census_income dataset](https://storage.cloud.google.com/cloud-ml-data/automl-tables/notebooks/census_income.csv) \n",
    "as your training data. We provide code below to copy the data into a bucket you own automatically. You are free to adjust the value of `GCS_STORAGE_BUCKET` as needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "GCS_STORAGE_BUCKET = 'gs://{}-codelab-data-storage'.format(PROJECT_ID)\n",
    "GCS_DATASET_URI = '{}/census_income.csv'.format(GCS_STORAGE_BUCKET)\n",
    "! gsutil ls $GCS_STORAGE_BUCKET || gsutil mb -l $COMPUTE_REGION $GCS_STORAGE_BUCKET\n",
    "! gsutil cp gs://cloud-ml-data-tables/notebooks/census_income.csv $GCS_DATASET_URI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Import data into the dataset, this process may take a while, depending on your data, once completed, you can verify the status by printing the dataset object. This time pay attention to the example_count field with 32561 records."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "FNVYfpoXJsNB"
   },
   "outputs": [],
   "source": [
    "import_data_operation = client.import_data(\n",
    "    dataset=dataset,\n",
    "    gcs_input_uris=gcs_input_uris\n",
    ")\n",
    "print('Dataset import operation: {}'.format(import_data_operation))\n",
    "\n",
    "# Synchronous check of operation status. Wait until import is done.\n",
    "import_data_operation.result()\n",
    "dataset = client.get_dataset(dataset_name=dataset.name)\n",
    "dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "QdxBI4s44ZRI"
   },
   "source": [
    "### Review the data specs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "v2Vzq_gwXxo-"
   },
   "outputs": [],
   "source": [
    "# List table specs\n",
    "list_table_specs_response = client.list_table_specs(dataset=dataset)\n",
    "table_specs = [s for s in list_table_specs_response]\n",
    "\n",
    "# List column specs\n",
    "list_column_specs_response = client.list_column_specs(dataset=dataset)\n",
    "column_specs = {s.display_name: s for s in list_column_specs_response}\n",
    "\n",
    "# Print Features and data_type:\n",
    "\n",
    "features = [(key, data_types.TypeCode.Name(value.data_type.type_code)) for key, value in column_specs.items()]\n",
    "print('Feature list:\\n')\n",
    "for feature in features:\n",
    "    print(feature[0],':', feature[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Table schema pie chart.\n",
    "\n",
    "type_counts = {}\n",
    "for column_spec in column_specs.values():\n",
    "  type_name = data_types.TypeCode.Name(column_spec.data_type.type_code)\n",
    "  type_counts[type_name] = type_counts.get(type_name, 0) + 1\n",
    "    \n",
    "plt.pie(x=type_counts.values(), labels=type_counts.keys(), autopct='%1.1f%%')\n",
    "plt.axis('equal')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "FNykW_YOYt6d"
   },
   "source": [
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kNRVJqVOL8h3"
   },
   "source": [
    "### Update dataset: assign a label column and enable nullable columns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-57gehId9PQ5"
   },
   "source": [
    "This section is important, as it is where you specify which column (meaning which feature) you will use as your label. This label feature will then be predicted using all other features in the row.\n",
    "\n",
    "AutoML Tables automatically detects your data column type. For example, for the ([census_income](https://storage.cloud.google.com/cloud-ml-data/automl-tables/notebooks/census_income.csv)) it detects `income_bracket` to be categorical (as it is just either over or under 50k) and `age` to be numerical. Depending on the type of your label column, AutoML Tables chooses to run a classification or regression model. If your label column contains only numerical values, but they represent categories, change your label column type to categorical by updating your schema."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "iRqdQ7Xiq04x"
   },
   "source": [
    "#### Update a column: Set to nullable"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "OCEUIPKegWrf"
   },
   "outputs": [],
   "source": [
    "update_column_response = client.update_column_spec(\n",
    "    dataset=dataset,\n",
    "    column_spec_display_name='income',\n",
    "    type_code='CATEGORY',\n",
    "    nullable=False,\n",
    ")\n",
    "update_column_response"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "GUqKi3tkqrgW"
   },
   "source": [
    "**Tip:** You can use `'type_code': 'CATEGORY'` in the preceding `update_column_spec_dict` to convert the column data type from `FLOAT64` `to  `CATEGORY`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nDMH_chybe4w"
   },
   "source": [
    "#### Update dataset: Assign a label"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "hVIruWg0u33t"
   },
   "outputs": [],
   "source": [
    "update_dataset_response = client.set_target_column(\n",
    "    dataset=dataset,\n",
    "    column_spec_display_name='income',\n",
    ")\n",
    "update_dataset_response"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "z23NITLrcxmi"
   },
   "source": [
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "FcKgvj1-Tbgj"
   },
   "source": [
    "### Creating a model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Pnlk8vdQlO_k"
   },
   "source": [
    "Once we have defined our datasets and features we will create a model.\n",
    "\n",
    "Specify the duration of the training. For example, `train_budget_milli_node_hours=1000` runs the training for one hour. \n",
    "\n",
    "If your Colab times out, use `client.list_models()` to check whether your model has been created. Then use model name to continue to the next steps. Run the following command to retrieve your model.\n",
    "\n",
    "```python\n",
    "    model = client.get_model(model_display_name=model_display_name) \n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "11izNd6Fu37N"
   },
   "outputs": [],
   "source": [
    "model_display_name = 'census_income_model'\n",
    "\n",
    "create_model_response = client.create_model(\n",
    "    model_display_name,\n",
    "    dataset=dataset,\n",
    "    train_budget_milli_node_hours=1000,\n",
    ")\n",
    "print('Create model operation: {}'.format(create_model_response.operation))\n",
    "# Wait until model training is done.\n",
    "model = create_model_response.result()\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "1wS1is9IY5nK"
   },
   "source": [
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model deployment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "n0lFAIkISf4K"
   },
   "source": [
    "**Important** : Deploy the model, then wait until the model FINISHES deployment.\n",
    "\n",
    "The model takes a while to deploy online. When the deployment code response = client.deploy_model(model_name=model.name) finishes, you will be able to see this on the UI. Check the [UI](https://console.cloud.google.com/automl-tables?_ga=2.255483016.-1079099924.1550856636) and navigate to the predict tab of your model, and then to the online prediction portion, to see when it finishes online deployment before running the prediction cell.You should see \"online prediction\" text near the top, click on it, and it will take you to a view of your online prediction interface. You should see \"model deployed\" on the far right of the screen if the model is deployed, or a \"deploying model\" message if it is still deploying. </span> "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "kRoHFbVnSk05"
   },
   "outputs": [],
   "source": [
    "client.deploy_model(model=model).result()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Verify if model has been deployed, check `deployment_state` field, it should show: `DEPLOYED`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = client.get_model(model_name=model.name)\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "0tymBrhLSnDX"
   },
   "source": [
    "Run the prediction, only after the model finishes deployment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "LMYmHSiCE8om"
   },
   "source": [
    "### Make an Online prediction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "G2WVbMFll96k"
   },
   "source": [
    "You can toggle exactly which values you want for all of the numeric features, and choose from the drop down windows which values you want for the categorical features.\n",
    "\n",
    "Note: If the model has not finished deployment, the prediction will NOT work.\n",
    "The following cells show you how to make an online prediction. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "yt-KXEEQu3-U"
   },
   "outputs": [],
   "source": [
    "#@title Make an online prediction: set the categorical variables{ vertical-output: true }\n",
    "from ipywidgets import interact\n",
    "import ipywidgets as widgets\n",
    "\n",
    "workclass_ids = ['Private', 'Self-emp-not-inc', 'Self-emp-inc', 'Federal-gov', 'Local-gov', 'State-gov', 'Without-pay', 'Never-worked']\n",
    "education_ids = ['Bachelors', 'Some-college', '11th', 'HS-grad', 'Prof-school', 'Assoc-acdm', 'Assoc-voc', '9th', '7th-8th', '12th', 'Masters', '1st-4th', '10th', 'Doctorate', '5th-6th', 'Preschool']\n",
    "marital_status_ids = ['Married-civ-spouse', 'Divorced', 'Never-married', 'Separated', 'Widowed', 'Married-spouse-absent', 'Married-AF-spouse']\n",
    "occupation_ids = ['Tech-support', 'Craft-repair', 'Other-service', 'Sales', 'Exec-managerial', 'Prof-specialty', 'Handlers-cleaners', 'Machine-op-inspct', 'Adm-clerical', 'Farming-fishing', 'Transport-moving', 'Priv-house-serv', 'Protective-serv', 'Armed-Forces']\n",
    "relationship_ids = ['Wife', 'Own-child', 'Husband', 'Not-in-family', 'Other-relative', 'Unmarried']\n",
    "race_ids = ['White', 'Asian-Pac-Islander', 'Amer-Indian-Eskimo', 'Other', 'Black']\n",
    "sex_ids = ['Female', 'Male']\n",
    "native_country_ids = ['United-States', 'Cambodia', 'England', 'Puerto-Rico', 'Canada', 'Germany', 'Outlying-US(Guam-USVI-etc)', 'India', 'Japan', 'Greece', 'South', 'China', 'Cuba', 'Iran', 'Honduras', 'Philippines', 'Italy', 'Poland', 'Jamaica', 'Vietnam', 'Mexico', 'Portugal', 'Ireland', 'France', 'Dominican-Republic', 'Laos', 'Ecuador', 'Taiwan', 'Haiti', 'Columbia', 'Hungary', 'Guatemala', 'Nicaragua', 'Scotland', 'Thailand', 'Yugoslavia', 'El-Salvador', 'Trinadad&Tobago', 'Peru', 'Hong', 'Holand-Netherlands']\n",
    "\n",
    "workclass = widgets.Dropdown(\n",
    "    options=workclass_ids, \n",
    "    value=workclass_ids[0],\n",
    "    description='workclass:'\n",
    ")\n",
    "\n",
    "education = widgets.Dropdown(\n",
    "    options=education_ids, \n",
    "    value=education_ids[0],\n",
    "    description='education:', \n",
    "    width='500px'\n",
    ")\n",
    " \n",
    "marital_status = widgets.Dropdown(\n",
    "    options=marital_status_ids, \n",
    "    value=marital_status_ids[0],\n",
    "    description='marital status:', \n",
    "    width='500px'\n",
    ")\n",
    "\n",
    "occupation = widgets.Dropdown(\n",
    "    options=occupation_ids, \n",
    "    value=occupation_ids[0],\n",
    "    description='occupation:', \n",
    "    width='500px'\n",
    ")\n",
    "\n",
    "relationship = widgets.Dropdown(\n",
    "    options=relationship_ids, \n",
    "    value=relationship_ids[0],\n",
    "    description='relationship:', \n",
    "    width='500px'\n",
    ")\n",
    "\n",
    "race = widgets.Dropdown(\n",
    "    options=race_ids, \n",
    "    value=race_ids[0],                           \n",
    "    description='race:', \n",
    "    width='500px'\n",
    ")\n",
    "\n",
    "sex = widgets.Dropdown(\n",
    "    options=sex_ids, \n",
    "    value=sex_ids[0],\n",
    "    description='sex:', \n",
    "    width='500px'\n",
    ")\n",
    "\n",
    "native_country = widgets.Dropdown(\n",
    "    options=native_country_ids, \n",
    "    value=native_country_ids[0],\n",
    "    description='native_country:', \n",
    "    width='500px'\n",
    ")\n",
    "\n",
    "display(workclass)\n",
    "display(education)\n",
    "display(marital_status)\n",
    "display(occupation)\n",
    "display(relationship)\n",
    "display(race)\n",
    "display(sex)\n",
    "display(native_country)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xGVGwgwXSZe_"
   },
   "source": [
    "Adjust the slides on the right to the desired test values for your online prediction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "bDzd5GYQSdpa"
   },
   "outputs": [],
   "source": [
    "#@title Make an online prediction: set the numeric variables{ vertical-output: true }\n",
    "\n",
    "age = 34 #@param {type:'slider', min:1, max:100, step:1}\n",
    "capital_gain = 40000 #@param {type:'slider', min:0, max:100000, step:10000}\n",
    "capital_loss = 3.8 #@param {type:'slider', min:0, max:4000, step:0.1}\n",
    "fnlwgt = 150000 #@param {type:'slider', min:0, max:1000000, step:50000}\n",
    "education_num = 9 #@param {type:'slider', min:1, max:16, step:1}\n",
    "hours_per_week = 40 #@param {type:'slider', min:1, max:100, step:1}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZAGi8Co-SU-b"
   },
   "source": [
    "Run the following cell, and then choose the desired test values for your online prediction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Kc4SKLLPSoKz"
   },
   "outputs": [],
   "source": [
    "inputs = {\n",
    "    'age': age,\n",
    "    'workclass': workclass.value,\n",
    "    'fnlwgt': fnlwgt,\n",
    "    'education': education.value,\n",
    "    'education_num': education_num,\n",
    "    'marital_status': marital_status.value,\n",
    "    'occupation': occupation.value,\n",
    "    'relationship': relationship.value,\n",
    "    'race': race.value,\n",
    "    'sex': sex.value,\n",
    "    'capital_gain': capital_gain,\n",
    "    'capital_loss': capital_loss,\n",
    "    'hours_per_week': hours_per_week,\n",
    "    'native_country': native_country.value,\n",
    "}\n",
    "\n",
    "prediction_result = client.predict(model=model, inputs=inputs)\n",
    "prediction_result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Get Prediction \n",
    "\n",
    "We extract the `google.cloud.automl_v1beta1.types.PredictResponse` object `prediction_result` and iterate to create a list of tuples with score and label, then we sort based on highest score and display it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions = [(prediction.tables.score, prediction.tables.value.string_value) for prediction in prediction_result.payload]\n",
    "predictions = sorted(predictions, key=lambda tup: (tup[0],tup[1]), reverse=True)\n",
    "print('Prediction is: ', predictions[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "O9CRdIfrS1nb"
   },
   "source": [
    "Undeploy the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "DWa1idtOS0GE"
   },
   "outputs": [],
   "source": [
    "undeploy_model_response = client.undeploy_model(model=model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TarOq84-GXch"
   },
   "source": [
    "### Batch prediction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Soy5OB8Wbp_R"
   },
   "source": [
    "#### Initialize prediction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "39bIGjIlau5a"
   },
   "source": [
    "Your data source for batch prediction can be GCS or BigQuery. \n",
    "\n",
    "For this tutorial, you can use: \n",
    "\n",
    "- [census_income_batch_prediction_input.csv](https://storage.cloud.google.com/cloud-ml-data/automl-tables/notebooks/census_income_batch_prediction_input.csv) as input source. \n",
    "\n",
    "Create a GCS bucket and upload the file into your bucket. \n",
    "\n",
    "Some of the lines in the batch prediction input file are intentionally left missing some values. \n",
    "The AutoML Tables logs the errors in the `errors.csv` file.\n",
    "Also, enter the UI and create the bucket into which you will load your predictions. \n",
    "\n",
    "The bucket's default name here is `automl-tables-pred` to be replaced with your own.\n",
    "\n",
    "**NOTE:** The client library has a bug. If the following cell returns a:\n",
    "\n",
    "`TypeError: Could not convert Any to BatchPredictResult` error, ignore it. \n",
    "\n",
    "The batch prediction output file(s) will be updated to the GCS bucket that you set in the preceding cells."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "GCS_BATCH_PREDICT_URI = '{}/census_income_batch_prediction_input.csv'.format(GCS_STORAGE_BUCKET)\n",
    "GCS_BATCH_PREDICT_OUTPUT = '{}/census_income_predictions/'.format(GCS_STORAGE_BUCKET)\n",
    "! gsutil cp gs://cloud-ml-data-tables/notebooks/census_income_batch_prediction_input.csv $GCS_BATCH_PREDICT_URI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Launch Batch prediction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_predict_response = client.batch_predict(\n",
    "    model=model, \n",
    "    gcs_input_uris=GCS_BATCH_PREDICT_URI,\n",
    "    gcs_output_uri_prefix=GCS_BATCH_PREDICT_OUTPUT,\n",
    ")\n",
    "print('Batch prediction operation: {}'.format(batch_predict_response.operation))\n",
    "# Wait until batch prediction is done.\n",
    "batch_predict_result = batch_predict_response.result()\n",
    "batch_predict_response.metadata"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Next steps\n",
    "\n",
    "Please follow latest updates on AutoML [here](https://cloud.google.com/automl/docs/)\n",
    "if you have any questions contact us at [cloud-automl-tables-discuss](https://groups.google.com/forum/#!forum/cloud-automl-tables-discuss)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "census_income_prediction.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
